<template>
  <view class="user-container">
    <view
      v-if="isAuthInfo"
      class="user-info-wrapper"
    >
      <view
        v-if="isLoading"
        class="loading"
      >
        加载中...
      </view>
      <view
        v-else
        class="user-info-content"
      >
        <!-- 用户头像 -->
        <view class="user-avatar">
          <image
            :src="getAvatarUrl()"
            class="avatar-image"
            @click="chooseImage"
          />
          <text class="avatar-tip">
            点击更换头像
          </text>
        </view>

        <!-- 用户信息表单 -->
        <view class="user-form">
          <view class="form-item">
            <text class="label">昵称：</text>
            <input
              v-model="userInfo.nickName"
              placeholder="昵称不可修改"
              class="input"
              readonly
              :disabled="true"
              @keydown.prevent
              @paste.prevent
              @cut.prevent
              style="caret-color: transparent;"
            >
          </view>

          <view class="form-item">
            <text class="label">
              真实姓名：
            </text>
            <input
              v-model="userInfo.realName"
              placeholder="请输入真实姓名"
              class="input"
            >
          </view>

          <view class="form-item">
            <text class="label required">
              手机号：
            </text>
            <input
              v-model="userInfo.userMobile"
              placeholder="请输入手机号"
              class="input"
              type="number"
            >
          </view>

          <view class="form-item">
            <text class="label">
              性别：
            </text>
            <picker
              :value="sexIndex"
              :range="sexOptions"
              class="picker"
              @change="sexChange"
            >
              <view class="picker-text">
                {{ sexOptions[sexIndex] || '请选择性别' }}
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label required">
              邮箱：
            </text>
            <input
              v-model="userInfo.userMail"
              placeholder="请输入邮箱"
              class="input"
              type="email"
            >
          </view>

          <!-- 新增旧密码输入 -->
          <view class="form-item">
            <text class="label">
              旧密码：
            </text>
            <input
              v-model="userInfo.oldPassword"
              type="password"
              placeholder="请输入旧密码"
              class="input"
            >
          </view>

          <!-- 修改现有密码输入项说明 -->
          <view class="form-item">
            <text class="label">
              新密码：
            </text>
            <input
              v-model="userInfo.loginPassword"
              type="password"
              placeholder="请输入新密码"
              class="input"
            >
          </view>

          <button
            class="save-btn"
            @click="saveUserInfo"
          >
            保存修改
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'

const picDomain = import.meta.env.VITE_APP_RESOURCES_URL

const isAuthInfo = ref(false)
const loginResult = ref(null)
// 在userInfo初始化部分增加oldPassword字段
const userInfo = ref({
  nickName: '',
  pic: null,
  realName: '',
  loginPassword: '',
  userMobile: null,
  userMail: null,
  sex: 'M',
  oldPassword: '' // 新增字段
})

const isLoading = ref(false)
const sexOptions = ['男', '女']

// 计算性别索引
const sexIndex = computed(() => {
  return userInfo.value.sex === 'M' ? 0 : 1
})

const getAvatarUrl = () => {
  if (userInfo.value.pic) {
    return userInfo.value.pic.startsWith('http') ? userInfo.value.pic : `${picDomain}${userInfo.value.pic}`
  }
  return '/static/images/icon/head04.png'
}

// 选择头像
// 选择头像
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      try {
        const filePath = res.tempFilePaths[0]
        const uploadResult = await uni.uploadFile({
          url: 'http://localhost:8080/user/upload/useravatar',
          filePath,
          name: 'file'
        })

        const response = JSON.parse(uploadResult.data)
        if (response.success) {
          // 修改为正确的属性名
          userInfo.value.pic = response.data
          await uni.showToast({
            title: '头像上传成功',
            icon: 'success'
          })
        } else {
          await uni.showToast({
            title: response.msg || '头像上传失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('头像上传失败:', error)
        await uni.showToast({
          title: '头像上传失败',
          icon: 'none'
        })
      }
    }
  })
}
// 性别选择
const sexChange = (e) => {
  userInfo.value.sex = e.detail.value === 0 ? 'M' : 'F'
}

onShow(() => {
  loginResult.value = uni.getStorageSync('loginResult')
  isAuthInfo.value = !!loginResult.value

  if (isAuthInfo.value) {
    isLoading.value = true
    uni.showLoading({ title: '加载中...' })

    http.request({
      url: '/user/info',
      method: 'GET'
    }).then(({ data }) => {
      // 处理null值转为空字符串
      userInfo.value = {
        ...userInfo.value,
        ...data,
        // 特殊处理需要字符串的字段
        userMobile: data.userMobile || '',
        userMail: data.userMail || ''
      }
      // 特殊处理性别默认值
      userInfo.value.sex = data.sex || 'M'
    }).finally(() => {
      isLoading.value = false
      uni.hideLoading()
    })
  }
})

const validateForm = () => {
  const requiredFields = [
    { field: 'userMobile', name: '手机号' },
    { field: 'userMail', name: '邮箱' }
  ]

  for (const { field, name } of requiredFields) {
    if (!userInfo.value[field]?.trim()) {
      uni.showToast({ title: `${name}不能为空`, icon: 'none' })
      return false
    }
  }

  // 手机号格式校验
  const mobileReg = /^1[3-9]\d{9}$/
  if (!mobileReg.test(userInfo.value.userMobile)) {
    uni.showToast({ title: '手机号格式不正确', icon: 'none' })
    return false
  }

  // 邮箱格式校验
  const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!emailReg.test(userInfo.value.userMail)) {
    uni.showToast({ title: '邮箱格式不正确', icon: 'none' })
    return false
  }

  return true
}

// 修改保存方法

const saveUserInfo = async () => {
  if (!validateForm()) return

  try {
    // 构造符合接口要求的请求体
    const requestData = {
      nickName: userInfo.value.nickName,
      pic: userInfo.value.pic,
      realName: userInfo.value.realName,
      loginPassword: userInfo.value.loginPassword,
      userMobile: userInfo.value.userMobile,
      sex: userInfo.value.sex,
      userMail: userInfo.value.userMail,
      oldPassword: userInfo.value.oldPassword
    }

    // 发送POST请求
    const response = await http.request({
      url: '/user/info',
      method: 'POST',
      data: requestData
    })

    if (response.success) {
      // 请求成功
      // 显示修改成功的提示信息，设置显示时长为 2000 毫秒（2 秒）
      const showToastDuration = 2000
      uni.showToast({
        title: '修改成功',
        duration: showToastDuration
      })

      // 清空密码字段
      // eslint-disable-next-line require-atomic-updates
      userInfo.value.loginPassword = ''
      // eslint-disable-next-line require-atomic-updates
      userInfo.value.oldPassword = ''

      // 使用 setTimeout 函数实现延迟跳转
      setTimeout(() => {
        // 使用 uni.switchTab 跳转到 tabBar 页面
        uni.switchTab({
          url: '/pages/user/user'
        })
      }, showToastDuration)
    } else {
      // 请求失败
      console.error('保存失败:', response.msg)
      await uni.showToast({
        title: response.msg || '修改失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('保存失败:', error)
    uni.showToast({
      title: error.message || '修改失败',
      icon: 'none'
    })
  }
}
</script>

<style scoped lang="scss">
.user-form {
  padding: 20rpx;

  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    padding: 20rpx;
    background: #fff;
    border-radius: 12rpx;

    .label {
      width: 160rpx;
      font-size: 30rpx;
      color: #666;
    }

    .input {
      flex: 1;
      height: 80rpx;
      padding: 0 20rpx;
      font-size: 30rpx;
      border: 1rpx solid #eee;
      border-radius: 8rpx;
    }

    .picker {
      flex: 1;
      .picker-text {
        height: 80rpx;
        line-height: 80rpx;
        padding: 0 20rpx;
        border: 1rpx solid #eee;
        border-radius: 8rpx;
      }
    }
  }

  .save-btn {
    margin-top: 40rpx;
    background-color: #007AFF;
    color: white;
    border-radius: 50rpx;
  }
}

.user-avatar {
  padding: 30rpx 0;
  text-align: center;

  .avatar-image {
    width: 200rpx;
    height: 200rpx;
    border-radius: 50%;
    border: 2rpx solid #eee;
  }

  .avatar-tip {
    display: block;
    margin-top: 20rpx;
    color: #666;
    font-size: 26rpx;
  }
}

.form-item .input[disabled] {
  background-color: #f8f8f8 !important;
  color: #666 !important;
  cursor: not-allowed !important;
  opacity: 1;
}
</style>
